package com.rdc.example.service.impl;

import com.rdc.example.bean.PageBean;
import com.rdc.example.bean.Result;
import com.rdc.example.bean.dto.NewsDTO;
import com.rdc.example.dao.NewsDao;
import com.rdc.example.dao.impl.NewsDaoImpl;
import com.rdc.example.entity.News;

import java.util.ArrayList;
import java.util.List;

public class NewsServiceImpl implements com.rdc.example.service.NewsService {

    NewsDao newsDao = new NewsDaoImpl();

    @Override
    public PageBean<NewsDTO> getNewsListByReceiverId(Integer receiverId, Integer currentPage, Integer pageSize) throws Exception {
        Integer pageBegin = (currentPage - 1) * pageSize;
        // 调用 dao 获取数据
        List<News> newsList = newsDao.getNewsListByReceiverId(receiverId, pageBegin, pageSize);
        Integer totalCount = newsDao.countNewsByReceiverId(receiverId);
        // 封装 PageBean
        PageBean<NewsDTO> pageBean = new PageBean<>();
        pageBean.setTotalCount(totalCount);
        pageBean.setRows(convertToDto(newsList));
        return pageBean;
    }

    @Override
    public Result updateIsRead(Integer id) throws Exception {
        if (id == null) {
            return Result.fail("消息Id不为空",null);
        }
        boolean update= newsDao.updateNews(id);
        return update?Result.success("更新成功",null)
                :Result.fail("更新失败",null);
    }

    // 将 News 实体列表转换为 NewsDTO 列表
    private List<NewsDTO> convertToDto(List<News> entities) {
        List<NewsDTO> dtos = new ArrayList<>();
        for (News entity : entities) {
            dtos.add(convertToDto(entity));
        }
        return dtos;
    }

    // 将单个 News 实体转换为 NewsDTO
    private NewsDTO convertToDto(News entity) {
        NewsDTO dto = new NewsDTO();
        dto.setId(entity.getId());
        dto.setSenderId(entity.getSenderId());
        dto.setReceiverId(entity.getReceiverId());
        dto.setContent(entity.getContent());
        dto.setIsRead(entity.getIsRead());
        dto.setCreatedAt(entity.getCreatedAt());
        return dto;
    }
}
